<?php  if(!defined('IN_APP')){exit();}
/**
 * MrPmvc基础模型
 * @author 狂奔的蜗牛
 * @email  672308444@163.com
 * @version alpha
 */
class BaseModel extends BaseUtil{
    private $objlist=array();
    protected $control;

    public function setControl($control){
           $this->control=$control;
    }
    public function __get($p){
        $p=strtolower($p.'Model');
        if(isset($this->objlist[$p])){
            return $this->objlist[$p];
        }else{
          return false;
        }
    }
    public function add_obj($obj,$modelName=null){
        $this->objlist[($modelName?$modelName:strtolower(get_class($obj)))]=$obj;
    }
    #Model高级功能开始
    
    /**
     * 根据字段映射数组$map读取$_POST中的数据
     * @param Array $map 字段映射数组
     */
    public function readData(Array $map){
           $data=array();
           $formdata=P();
           foreach ($formdata as $form=>$val)
          { 
                 if(isset($map[$form])){
                     $data[$map[$form]]=$val;
                 }
           }
           return $data;
    }
    
    
    public function check(Array $rule,Array $data){
           $this->msg='';
           foreach ($rule as $col=>$val) {
               if($val['rule']){
                   #有规则但是没有数据，就补上空数据，然后进行验证
                   if(!isset($data[$col])){$data[$col]='';}
                   
                   #函数验证
                   if(strpos($val['rule'], '/')===FALSE){
                        #返回False使用rule里面的错误信息
                        if($this->{$val['rule']}($data[$col],$data)===FALSE){
                               $this->msg=$val['msg'];
                               return FALSE;
                         }
                         #返回-1，使用函数自定义错误信息
                        if($this->{$val['rule']}($data[$col],$data)===-1){
                               return FALSE;
                         }
                   }else{
                   #正则表达式验证
                  //echo 'preg_match('.$val['rule'].', '.$data[$col].')';
                  //var_dump(preg_match($val['rule'], $data[$col]));
                         if(!preg_match($val['rule'], $data[$col])){
                               $this->msg=$val['msg'];
                               return FALSE;
                         }
                   }
               }
           }
           return TRUE;
    }
    
    public function _insert(Array $data){
               $sql=$this->getInsertSQL($data);
               $data=$this->fixValues($data);
               return $this->db->insert($sql,$data);
    }
    
    public function _update(Array $data){
              $sql=$this->getUpdateSQL($data);
              $data=$this->fixValues($data);
              return $this->db->update($sql,$data);
    }
    
    public function getByCol($col,$val){
           return $this->db->row("select * from {$this->table} where {$col}=?",array($val));
    } 
    
    public function setColByPk($col,$val,$pid){
            $pid=intval($pid);
            return $this->db->update("{$this->table} set {$col}=? where {$this->pk}=?",array($val,$pid));
    }
    
    public function setColByPks($col,$val,Array $pids){
           $ina=array();
           $values[]=$val;
           foreach ($pids as $pid){
              $ina[]='?';
              $values[]=$pid;
           }
           $instr=implode(',', $ina);
           return $this->db->update("{$this->table} set {$col}=? where {$this->pk} in({$instr})",$values);
    }
    protected  function fixValues($data){
              $data2=array();
              foreach ($data as $key=>$value) {
                  $data2[':'.$key]=$value;
              }
              return  $data2;
    }
    private function getUpdateSQL(Array $data){
             if(!count($data)){return false;}
             if(isset($data[$this->pk])){
                 $pk=intval($data[$this->pk]);
                 unset($data[$this->pk]);
                if($pk){
                     $set=array();
                     foreach ($data as $key=>$value) {
                         $set[]=$key."=:{$key}";
                     }
                     $sql="{$this->table} set ".implode(',', $set)." where {$this->pk}=:{$this->pk}";
                     return $sql;
                }
             }
             return FALSE;
    }
    private function getInsertSQL(Array $data){
             if(!count($data)){return '';}
             $cols=array();$values=array();
             foreach ($data as $key=>$value) {
                 $cols[]=$key;
                 $values[]=":{$key}";
             }
             $str="{$this->table}(".implode(',', $cols).") values(".implode(',', $values).")";
             return $str;
    }
}